#include <iostream>
#include <wiringPi.h>
#include <stdio.h>

#include "sxcom.h"

#define DELAY 1000000 

#define IN_PIN 0
#define OUT_PIN 16 

using namespace std;

int main()
{
	wiringPiSetup(); 

	pinMode(IN_PIN, INPUT);		// Setup pins here
	pinMode(OUT_PIN, OUTPUT);	// Setup pins here
	//cout << "TEST";
	
	
	uint8_t CUBE_ID=0;
 
	FILE *file = fopen("cube.id", "rb");
	if(file)
	{
		fread((void*)(&CUBE_ID), 1, 1, file); 
		CUBE_ID = CUBE_ID - 65; 
		cout << "This Cube's ID: " << (int)CUBE_ID;
	}else{
		return -1; 
	} 
	
	
	initSXCOM(CUBE_ID);
		

	bool state = false; 
	if(CUBE_ID == 0)
		state = false; 
	else
		state = true; 

	// Game Loop
	while(1)
	{
		if(state)
		{
			// Turn light on
			digitalWrite(OUT_PIN, 1);
			for(int i=0; i<DELAY; i++)
			{
				// Check state 
				if(digitalRead(IN_PIN) > 0)
				{
					// Turn light off
					digitalWrite(OUT_PIN, 0);
					i = DELAY; 
					state = false;
					uint8_t cptr = 'X'; 
					if(CUBE_ID == 0)
						msgSend(createMessage(0, 1, 0, 1, &cptr));  
					else
						msgSend(createMessage(0, 0, 1, 1, &cptr));  
				}
			}
			


		}
		else
		{
			// Turn light off
			digitalWrite(OUT_PIN, 0);
			if(msgRec != NULL)
			{
				state = true; 
			}


		}

				 	
	
	}
		

	return 0; 	
}
